//% color="#0586C4" iconWidth=50 iconHeight=40
namespace XKG_wifi{
    //% block="行空板wifi:ip地址,输入ssid:[ssid],password:[password]" blockType="command"
    //% ssid.shadow="normal" ssid.defl="wifi名称"
    //% password.shadow="normal" password.defl="wifi密码"
    export function XKB_wifi(parameter: any, block: any) {
        let ssid=parameter.ssid.code
        let password=parameter.password.code
        Generator.addImport(`import subprocess\nimport time`)
        Generator.addCode(`def ip_address():
        #获取IP地址的命令      
        ip_command=f'sudo nmcli device show'
        # 执行ipconfig命令并获取输出
        ip_output = subprocess.check_output(ip_command, shell=True, text=True)
        # 从输出中提取IP地址信息
        ip_address_start = ip_output.find("IP4.ADDRESS[1]")+len("IPv4 地址") + 1
        ip_address_end = ip_output.find("\\r\\n", ip_address_start)
        ip_address =ip_output[ip_address_start:ip_address_end].strip().replace(" ", "")
        ip_ress= ip_address[7:24]
        return ip_ress`) 
        Generator.addCode(`
# 构建连接Wi-Fi的命令       
connect_command = f'sudo nmcli dev wifi connect "${ssid}" password "${password}" ifname wlan0'
try:
    # 执行连接命令
    subprocess.run(connect_command, check=True, shell=True)
    print("Wi-Fi连接成功!")
    # 等待一段时间，确保连接完成
    time.sleep(5)           
except subprocess.CalledProcessError as e:
    print(f"Wi-Fi连接失败: {e}")
        `)

    } 
    //% block="行空板wif:ip地址" blockType="reporter"
    export function XKB_IP(parameter: any, block: any) { 
              
        Generator.addCode(`ip_address()`)
    } 
    
}

